import {uuid} from '@/assets/js/utils/Uuid'
import * as turf from '@turf/turf';

const sourceId = 'measure-source';
const layer_point_Id = 'measure-point-source';
const layer_line_Id = 'measure-line-source';
const layer_polygon_Id = 'measure-polygon-source';

export default class Measure {

  /**
   * 构造方法
   * @param mapbox
   */
  constructor(mapbox, options) {
    this._map = mapbox.getMap();
    this._hgcMapBoxUtil = mapbox;
    this._points = [];
    this._pops = [];
    this._drawMode = 0;
    this._layerInit = undefined;
    this._data = {
      type: 'FeatureCollection',
      features: []
    }    //数据
    this._opt = options;
    this._plotMode = undefined;
    this._isOver = undefined;
  }

  setPlotMode() {
    this._plotMode = true
  }

  /**
   * 设置绘制模式 0测距 1测面积
   * @param action
   */
  setDrawAction(action) {
    console.log(action)
    this._drawMode = action;
    this._isOver = false;
    this._startDraw();
    this._addTrackFeature();
  }

  /**
   * 开始绘制准备工作
   * @private
   */
  _startDraw() {
    //添加数据源
    if (this._layerInit) {
      this._map.on('click', this._mouseClickEvent);
      this._map.on('mousemove', this._mouseMoveEvent);
      this._map.on('contextmenu', this._mouseContextEvent);
      this._map.doubleClickZoom.disable();
      this._map.getCanvas().style.cursor = 'crosshair';
      return;
    }
    this._hgcMapBoxUtil.addSource(sourceId, {type: 'geojson', data: this._data});
    this._hgcMapBoxUtil.addLayer(layer_point_Id, {
      id: layer_point_Id,
      type: "circle",
      source: sourceId,
      paint: {
        "circle-radius": 6,
        "circle-color": "#FF5050"
      },
      filter: ['==', '$type', 'LineString']
    });
    this._hgcMapBoxUtil.addLayer(layer_line_Id, {
      id: layer_line_Id,
      type: "line",
      source: sourceId,
      layout: {
        "line-cap": "round",
        "line-join": "round"
      },
      paint: {
        "line-color": "#FD8045",
        "line-width": 2
      }
    });
    this._hgcMapBoxUtil.addLayer(layer_polygon_Id, {
      id: layer_polygon_Id,
      type: "fill",
      source: sourceId,
      layout: {},
      paint: {
        "fill-color": "#FD8045",
        "fill-opacity": 0.45
      },
      filter: ['==', '$type', 'Polygon']
    });
    this._mouseClickEvent = this._mouseClickEvent.bind(this);
    this._mouseMoveEvent = this._mouseMoveEvent.bind(this);
    this._mouseContextEvent = this._mouseContextEvent.bind(this);
    this._map.on('click', this._mouseClickEvent);
    this._map.on('mousemove', this._mouseMoveEvent);
    this._map.on('contextmenu', this._mouseContextEvent);
    this._map.doubleClickZoom.disable();
    this._map.getCanvas().style.cursor = 'crosshair';
    this._layerInit = true;
  }

  /**
   * 添加跟踪图层的要素数据
   * @private
   */
  _addTrackFeature() {
    this._points = [];
    //线要素
    this._line = {
      id: uuid(),
      type: "Feature",
      geometry: {
        type: "LineString",
        coordinates: []
      },
      properties: {
        color: "#33C9EB", // blue
        length: ""
      }
    }
    //面要素
    this._polygon = {
      id: uuid(),
      type: "Feature",
      geometry: {
        type: "Polygon",
        coordinates: [[]]
      },
      properties: {
        color: "#33C9EB", // blue
        length: ""
      }
    }
    this._data.features.push(this._line);
    this._data.features.push(this._polygon);
  }

  /**
   * 绘制结束
   * @private
   */
  _endDraw() {
    this._map.off('click', this._mouseClickEvent);
    this._map.off('mousemove', this._mouseMoveEvent)
    this._map.off('contextmenu', this._mouseContextEvent);
    setTimeout(() => {
      this._map.doubleClickZoom.enable();
    }, 500);
  }

  /**
   * 点击事件
   * @param e
   * @private
   */
  _mouseClickEvent(e, islast) {
    //console.log('click')
    if (this._isOver) {
      return;
    }
    this._points.push([e.lngLat.lng, e.lngLat.lat]);
    const point = {
      type: "Feature",
      geometry: {type: "Point", coordinates: [e.lngLat.lng, e.lngLat.lat]},
      properties: {id: uuid(), properties: {length: ""}}
    };
    this._data.features.push(point);
    this._line.geometry.coordinates = this._points;
    if (!this._plotMode) {
      if (this._drawMode === 0) {  //绘制线
        this._drawLineText(e, islast);
      } else if (islast) {   //绘制面
        this._drawAreaText(e);
      }
    }

    this._refreshData();
  }


  /**
   * 绘制线文本
   * @param e
   * @param islast
   * @private
   */
  _drawLineText(e, islast) {
    let distance = turf.lineDistance(this._line);
    let value = distance >= 1 ? `${distance.toFixed(2)}公里` : `${(distance * 1000).toFixed(2)}米`;
    let popup = new mapboxgl.Popup({closeButton: false, closeOnClick: false}).setLngLat([e.lngLat.lng, e.lngLat.lat])
      .setHTML(islast ? `<div class='measurePopupSum'>总长：<span>${value}</span></div>` : (distance === 0 ? `<div class='measurePopup'>起点</span></div>` : `<div class='measurePopup'><span>${value}</span></div>`))
      .addTo(this._map);
    this._pops.push(popup);
  }

  /**
   * 绘制面文本
   * @param e
   * @private
   */
  _drawAreaText(e) {
    let area = turf.area(this._polygon);
    let value = area >= 10000 ? `${(area / 1000000).toFixed(3)}平方千米` : `${area.toFixed(3)}平方米`;
    let popupHtml = `<div class='measurePopupSum'><span>面积：</span>${value}</div>`;
    let b = new mapboxgl.LngLatBounds(this._points[0], this._points[0]);
    this._points.reduce(function (bounds, coord) {
      return bounds.extend(coord);
    }, b);
    var pop = new mapboxgl.Popup({
      closeButton: false, closeOnClick: false
    }).setLngLat(b.getCenter()).setHTML(popupHtml).addTo(this._map);
    this._pops.push(pop);
  }

  /**
   * 鼠标移动（跟踪图层）
   * @param e
   * @private
   */
  _mouseMoveEvent(e) {
    if (this._points.length === 0 || this._isOver) {
      return;
    }
    const array = this._points.concat(this._drawMode === 0 ? [[e.lngLat.lng, e.lngLat.lat]] : [[e.lngLat.lng, e.lngLat.lat], this._points[0]]);
    this._line.geometry.coordinates = array;
    if (this._drawMode === 1) {
      this._polygon.geometry.coordinates = [array];
    }
    //console.log('move')
    this._refreshData();
  }

  /**
   * 双击结束
   * @param e
   * @private
   */
  _mouseContextEvent(e) {
    //console.log('contextmenu')
    this._endDraw();
    if (this._points.length === 0) {
      return;
    }
    this._mouseClickEvent(e, true);
    this._map.getCanvas().style.cursor = '';
    this._isOver = true;
    //this.setDrawAction(1)
  }

  /**
   * 刷新数据
   * @private
   */
  _refreshData() {
    const source = this._map.getSource(sourceId);
    if (source) {
      source.setData(this._data);
    }
  }

  /**
   * 清除图层
   */
  clearMeasure() {
    this._hgcMapBoxUtil.removeTileLayer(sourceId);
    this._pops.forEach(pop => {
      pop.remove();
    })
    this._layerInit = false;
    this._data.features =[]
  }

}
